package com.apexsoft.assets.base.utils;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @author Jian Shen
 * @version V1.0
 * @date 2019/2/14
 */
@Slf4j
@Component
public class TokenUtils {

    @Getter
    private static String key;

    @Value("${application.sso.key:}")
    public void setKey(String key){
        TokenUtils.key=key;
    }

    public static String buildToken(String userId, String key, boolean useDate, String dateFormat) {
        if(StringUtils.isEmpty(key)){
            key=getKey();
        }
        String raw = userId + key ;
        if (useDate) {
            LocalDate localDate = LocalDate.now();
            String formattedDate = localDate.format(DateTimeFormatter.ofPattern(dateFormat));
            raw += formattedDate;
        }
        String token = Md5Utils.md5Encode2Hex(raw);
        return token;
    }

    public static String buildToken(String userId) {
        String key = getKey();
        return buildToken(userId, key, false, "");
    }

    public static boolean validToken(String userId, String token, String key, boolean useDate, String dateFormat) {
        String expectedToken = buildToken(userId, key, useDate, dateFormat);
        log.info("当前账号为 {} 期望的token为 {}， 实际的token为 {}", userId, expectedToken, token);
        return expectedToken.equals(token);
    }

    public static boolean validToken(String userId, String token, boolean useDate, String dateFormat) {
        return validToken(userId, token, getKey(), false, "");
    }

    public static boolean validToken(String userId, String token) {
        return validToken(userId, token, false, "");
    }
}
